<!--
 * @Description: 登录弹框内容
 * @Author: 56208
 * @Date: 2025/4/22 14:02
 * @LastEditors: 56208
 * @LastEditTime: 2025/4/22 14:02
 * @FilePath: D:/vue3-electron-music/src/renderer/src/components/header\loginDialog.vue
 -->

<template>
  <el-dialog v-model="loginDialogVisible" title="登录" width="600" @close="handleClose">
    <div class="d-al-jt flex-d-col">
      <img :src="qrCode" alt="" height="250" width="250" />
      <div v-if="qrCodeStatus.nickname" class="text-14 mt-24">{{ qrCodeStatus.nickname }}</div>
      <div class="text-18 mt-24 font-w-400">{{ qrCodeStatus.message }}</div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@renderer/store/userInfo'
const { proxy } = getCurrentInstance() as any
const userStore = useUserStore()

const emit = defineEmits(['close'])

const loginDialogVisible = ref(false)
// 二维码
const qrCode = ref('')
// 二维码状态
const qrCodeStatus = ref({})
// 定时器
let timer = null

// 获取二维码状态
function checkLoginStatus(key) {
  timer = setInterval(async () => {
    qrCodeStatus.value = await proxy.requestApi.login_code_status(key)
    // 二维码过期
    if (qrCodeStatus.value.code === 800) {
      closeFunc()
      await handleUser()
      return
    }
    // 授权中
    if (qrCodeStatus.value.code === 802) {
      qrCode.value = qrCodeStatus.value.avatarUrl
      return
    }
    // 登录成功
    if (qrCodeStatus.value.code === 803) {
      localStorage.setItem('cookie', qrCodeStatus.value.cookie)
      userStore.setCookie(qrCodeStatus.value.cookie)
      userStore.setLoginStatus(proxy)
      closeFunc()
      return
    }
  }, 2000)
}

// 清空定时器和相关信息
function closeFunc() {
  if (timer) {
    qrCodeStatus.value = {}
    clearInterval(timer)
    timer = null
  }
}

function handleClose() {
  closeFunc()
  emit('close')
}

// 扫码登录逻辑
const getQrCodeFunc = async () => {
  const keyRes = await proxy.requestApi.login_key()
  if (keyRes.code !== 200) {
    ElMessage.error('调用失败')
    return
  }
  const codeRes = await proxy.requestApi.login_code(keyRes.data.unikey)
  if (codeRes.code !== 200) {
    ElMessage.error('调用失败')
    return
  }
  qrCode.value = codeRes.data.qrimg
  loginDialogVisible.value = true
  checkLoginStatus(keyRes.data.unikey)
}

onMounted(() => {
  getQrCodeFunc()
})
</script>

<style scoped lang="less">
</style>
